#include"head.h"

int tackle_register(int socket, MYSQL *db, TLV *TLV_RECV) {
    int user_id = -1;
    TLV *TLV_T = (TLV *)malloc(sizeof(TLV));
    memset(TLV_T, 0, sizeof(TLV));
    // 1. 解析用户名和密码（各8字节）
    char username[9] = {0};
    char password[9] = {0};
    memcpy(username,TLV_RECV ->username, 8);
    memcpy(password,TLV_RECV ->value , 8);

    // 2. 检查用户名是否已存在
    MYSQL_STMT *stmt = mysql_stmt_init(db);
    const char *query = "SELECT id FROM users WHERE username = ? AND isDelete = 0";
    mysql_stmt_prepare(stmt, query, strlen(query));
    MYSQL_BIND param = {0};
    param.buffer_type = MYSQL_TYPE_STRING;
    param.buffer = username;
    param.buffer_length = 8;
    mysql_stmt_bind_param(stmt, &param);

    if (mysql_stmt_execute(stmt) || mysql_stmt_store_result(stmt)) {
        fprintf(stderr, "查询失败: %s\n", mysql_stmt_error(stmt));
        goto cleanup;
    }

    if (mysql_stmt_num_rows(stmt) > 0) {
        TLV_T->type = 0xFF; // 用户名已存在
        user_id = -2;
        goto cleanup;
    }
    mysql_stmt_close(stmt);

    // 3. 生成盐值和密码哈希
    unsigned char salt[32];
    unsigned char hash[SHA256_DIGEST_LENGTH];
    create_salt(salt);
    create_encrypt(salt, password, hash);

    // 4. 插入新用户（使用预处理语句）
    stmt = mysql_stmt_init(db);
    query = "INSERT INTO users (username, password, saltNum, ciphertext) VALUES (?, ?, ?, ?)";
    mysql_stmt_prepare(stmt, query, strlen(query));

    MYSQL_BIND params[4] = {0};
    params[0].buffer_type = MYSQL_TYPE_STRING;
    params[0].buffer = username;
    params[0].buffer_length = 8;

    params[1].buffer_type = MYSQL_TYPE_STRING;
    params[1].buffer = password; // 明文密码（实际应只存哈希）
    params[1].buffer_length = 8;

    params[2].buffer_type = MYSQL_TYPE_BLOB;
    params[2].buffer = salt;
    params[2].buffer_length = 32;

    params[3].buffer_type = MYSQL_TYPE_BLOB;
    params[3].buffer = hash;
    params[3].buffer_length = SHA256_DIGEST_LENGTH;

    mysql_stmt_bind_param(stmt, params);
    if (mysql_stmt_execute(stmt)) {
        fprintf(stderr, "注册失败: %s\n", mysql_stmt_error(stmt));
        goto cleanup;
    }

    user_id = mysql_stmt_insert_id(stmt); // 获取新用户ID
    TLV_T->type = 0x30; // 注册成功
strncpy(TLV_T->token,TLV_RECV->token,65);
TLV_T->seq=user_id;
TLV_T->length=0;
cleanup:
    if (user_id <= 0) TLV_T->type = 0xFF;
    sendTlv(socket, TLV_T);
    if (stmt) mysql_stmt_close(stmt);
    free(TLV_T);
    return user_id;
}
